package day19;

import java.awt.*;

import java.awt.event.*;
import javax.swing.*;
import java.io.*;

	/**
	 * @author Wangpeihu
	 */
public class SplitPic implements ActionListener {
	
	JFrame jf = new JFrame("FileSplit");
	private JTextField jt1 = new JTextField(20);
	private JTextField jt2 = new JTextField(20);
	JFileChooser jfc = new JFileChooser();
	private String dz;
	public void actionPerformed(ActionEvent e) {
		String comm = e.getActionCommand();
		if ("open".equals(comm)) {
			this.open();
			jt1.setText(dz);
			
		} else if ("split".equals(comm)) {
			try {
				this.split();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			try {
				this.sum();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public void open(){
		Component parent = null;
		    int returnVal = jfc.showOpenDialog(parent);
		    if(returnVal == JFileChooser.APPROVE_OPTION) {
		       dz =(jfc.getCurrentDirectory()+"/"+jfc.getSelectedFile().getName());
		    }
	}
	
	public SplitPic() {
		jf.setLayout(new FlowLayout());
		JLabel jl1 = new JLabel("Address:");
		jf.add(jl1);
		jf.add(jt1);
		JLabel jl2 = new JLabel("size:");
		jf.add(jl2);
		JButton jb1 = new JButton("open");
		jb1.addActionListener(this);
		JButton jb2 = new JButton("split");
		jb2.addActionListener(this);
		JButton jb3 = new JButton("sum");
		jb3.addActionListener(this);
		jf.add(jt2);
		jf.add(jb1);
		jf.add(jb2);
		jf.add(jb3);
		jf.setLocation(400, 400);
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void sum() throws Exception {
		for (int j = 0; j < 6; j++) {
			FileInputStream fis = new FileInputStream(dz+ j);
			for (int i = 0; i < 10; i++) {
				int f = Integer.parseInt(jt2.getText());
				byte[] b = new byte[f];
				FileOutputStream fos = new FileOutputStream(dz, true);
				int num = fis.read(b);
				if (num == -1)
					break;
				fos.write(b, 0, num);
				fos.close();
			}
			fis.close();
		}
	}

	public void split() throws Exception {
		FileInputStream fis = new FileInputStream(dz);			//采用输入流，
		for (int i = 0; i < 10; i++) {					
			int f = Integer.parseInt(jt2.getText());		//
			byte[] b = new byte[f];
			FileOutputStream fos = new FileOutputStream(dz+ i);
			int num = fis.read(b);
			if (num == -1)
				break;
			fos.write(b, 0, num);
			fos.close();
		}
		fis.close();
	}

	public static void main(String[] args) {
		new SplitPic();
	}
}